package com.lawliet.example.service.system.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lawliet.example.model.User;
import com.lawliet.example.model.system.SysUser;
import com.lawliet.example.model.system.SysUserRole;
import com.lawliet.example.repository.system.SysUserMapper;
import com.lawliet.example.repository.system.SysUserRoleMapper;
import com.lawliet.example.service.system.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    /**
     * 新增用户
     * @param sysUser 用户对象
     * @param roleId 角色id
     */
    @Override
    @Transactional
    public void addUserInfo(SysUser sysUser, Long roleId) {
        //添加用户信息
        this.save(sysUser);
        //添加用户角色对应关系
        Long userId = sysUser.getId();
        SysUserRole userRoleRelation = new SysUserRole();
        userRoleRelation.setUserId(userId);
        userRoleRelation.setRoleId(roleId);
        sysUserRoleMapper.insert(userRoleRelation);
    }

    /**
     * 删除用户
     * @param ids 主键id字符串
     */
    @Override
    @Transactional
    public void deleteBatch(String ids) {
        //删除用户
        this.deleteBatch(ids);
        List<String> idList =  Arrays.asList(ids.split(","));
        //清除用户角色对应关系
        for(String id : idList){
            LambdaQueryWrapper<SysUserRole> con = new LambdaQueryWrapper<>();
            con.eq(SysUserRole::getUserId,Long.parseLong(id));
            sysUserRoleMapper.delete(con);
        }
    }


    /**
     * 绑定用户角色
     * @param userId 用户id
     * @param roleIds 角色id字符串
     */
    @Override
    @Transactional
    public void userBindRole(Long userId, String roleIds) {
        //删除原先的绑定关系
        LambdaQueryWrapper<SysUserRole> con = new LambdaQueryWrapper<>();
        con.eq(SysUserRole::getUserId,userId);
        sysUserRoleMapper.delete(con);
        List<String> roleIdList =  Arrays.asList(roleIds.split(","));
        //添加角色用户对应关系
        for(String roleId : roleIdList){
            SysUserRole userRoleRelation = new SysUserRole();
            userRoleRelation.setUserId(userId);
            userRoleRelation.setRoleId(Long.parseLong(roleId));
            sysUserRoleMapper.insert(userRoleRelation);
        }
    }

}
